#include "util.hpp"
#include "level.hpp"
#include "message.hpp"
#include "formatter.hpp"
#include "sink.hpp"
#include "logger.hpp"
#include "buffer.hpp"
#include <unistd.h>
/* 拓展一个以时间作为成为文件滚动切换类型的日志落地模块
    1.以时间进行文件滚动，实际上是以时间段进行文件滚动
        实现思想：以当前系统时间，取模时间段大小，可以得到当前时间段是第几个时间段，
        每次与当前系统时间取模，判断与当前文件的时间段是否一致，不一致就代表不是一个时间段，就切换文件
*/
enum class TimeGap{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

  //落地方向：滚动文件(以时间进行滚动)
    class RollByTimeSink : public lcglog::LogSink{
        public:
            //构造时将文件名传入，并且打开文件，将操作句柄管理起来，通过文件句柄管理文件
            RollByTimeSink(const std::string& pathname, TimeGap gap_type):_pathname(pathname){
                switch(gap_type){
                    case TimeGap::GAP_SECOND: _gap_size = 1;    break;
                    case TimeGap::GAP_MINUTE: _gap_size = 60;   break;
                    case TimeGap::GAP_HOUR: _gap_size = 3600;   break;
                    case TimeGap::GAP_DAY: _gap_size = 3600*24; break;
                }
                //_cur_gap = (gap_type == TimeGap::GAP_SECOND) ?lcglog::util::Date::now() : lcglog::util::Date::now() % _gap_size;//获取当前是第几个时间段
                _cur_gap = (_gap_size == 1) ?lcglog::util::Date::now() : lcglog::util::Date::now() % _gap_size;//获取当前是第几个时间段

                std::string filename = createNewFile();
                lcglog::util::File::createDirectory(lcglog::util::File::path(filename));
                _ofs.open(filename, std::ios::binary | std::ios::app);
                assert(_ofs.is_open());
            }
            //将日志消息写入到指定文件--判断当前时间是否是当前文件的时间段，不是就切换文件
            void log(const char* data, size_t len){
                time_t cur = lcglog::util::Date::now();//获取系统当前时间
                if((cur % _gap_size) != _cur_gap){
                    _ofs.close();//关闭原来已经打开的文件
                    std::string filename = createNewFile();
                    _ofs.open(filename, std::ios::binary | std::ios::app);
                    assert(_ofs.is_open());
                }

                _ofs.write(data, len);
                assert(_ofs.good());
            }
        private:
            //进行大小判断，超过指定大小则创建新文件
            std::string createNewFile(){
                time_t t = lcglog::util::Date::now();
                struct tm lt;
                localtime_r(&t, &lt);
                std::stringstream filename;
                filename << _pathname;
                filename << lt.tm_year+1900;
                filename << lt.tm_mon+1;
                filename << lt.tm_mday;
                filename << lt.tm_hour;
                filename << lt.tm_min;
                filename << lt.tm_sec;
                filename << ".log";

                return filename.str();
            }
        private:
            //通过基础文件名+拓展文件名（以时间生成）,组成一个实际的当前输出文件名
            std::string _pathname;
            std::ofstream _ofs; //操作句柄
            size_t _cur_gap;//当前是第几个时间段
            size_t _gap_size;//时间段的大小
    };

void test_log(){
    // std::cout << "开始文件写入\n";
    // sleep(10);
    lcglog::Logger::ptr logger = lcglog::LoggerManger::getInstance().getLogger("async_logger");
    logger->debug(__FILE__, __LINE__, "%s", "测试日志");
    logger->info(__FILE__, __LINE__, "%s", "测试日志");
    logger->warn(__FILE__, __LINE__, "%s", "测试日志");
    logger->error(__FILE__, __LINE__, "%s", "测试日志");
    logger->fatal(__FILE__, __LINE__, "%s", "测试日志");
     size_t count = 0;
    while(count <= 100000){
        logger->fatal(__FILE__, __LINE__, "测试日志-%d",count++);
    }
}
int main()
{
    // /*读取文件数据，一点一点写入缓冲区，最终将缓冲区数据写入文件，判断生成的新文件与原文件是否一致，一致的话表示该模块功能正常*/
    // std::ifstream ifs("./logfile/test_file", std::ios::binary);
    // if(ifs.is_open() == false){
    //     std::cout << "open fail!\n";
    //     return -1;
    // }
    // ifs.seekg(0, std::ios::end);//读写位置跳转到文件末尾
    // size_t fsize = ifs.tellg();//获取当前读写位置相对于起始位置的偏移量
    // ifs.seekg(0, std::ios::beg);//重新跳转到起始位置
    // std::string body;
    // body.resize(fsize);
    // ifs.read(&body[0], fsize);
    // if(ifs.good() == false){
    //     std::cout << "read error!\n";
    //     return -1;
    // }
    // ifs.close();

    // lcglog::Buffer buffer;
    // for(size_t i=0; i<body.size(); i++){
    //     buffer.push(&body[i], 1);
    // }
    // std::cout << fsize <<std::endl;

    // std::ofstream ofs("./logfile/tmp_file", std::ios::binary);
    // size_t rsize = buffer.readAbleSize();
    // if(ofs.is_open() == false){
    //     std::cout << "open fail!\n";
    //     return -1;
    // }
    // std::cout << buffer.readAbleSize() << std::endl;

    // //ofs.write(buffer.begin(), buffer.readAbleSize());
    // for(size_t i=0; i<rsize; i++){
    //     ofs.write(buffer.begin(), 1);
    //     if(ofs.good() == false){
    //         std::cout << "write error!\n";
    //         return  -1;
    //     }
    //     buffer.moveReader(1);
    // }
    // ofs.close();

    // std::string logger_name = "sync_logger";
    // lcglog::LogLevel::value level =  lcglog::LogLevel::value::ERROR;//只有输出等级是ERROR及以上等级的日志消息才会输出
    // lcglog::Formatter::ptr fmt(new lcglog::Formatter("[%d{%H:%M:%S}][%c][%p][%f:%l]%T%m%n"));
    // lcglog::LogSink::ptr lsp_stdout = lcglog::SinKFactory::create<lcglog::StdoutSink>();
    // lcglog::LogSink::ptr lsp_file = lcglog::SinKFactory::create<lcglog::FileSink>("./logfile/test_file");
    // lcglog::LogSink::ptr lsp_rollfile = lcglog::SinKFactory::create<lcglog::RollBySizeSink>("./logfile/roll-", 1024*1024);
    // std::vector<lcglog::LogSink::ptr> sinks = {lsp_stdout, lsp_file, lsp_rollfile};
    // lcglog::Logger::ptr logger(new lcglog::SyncLogger(logger_name, level, fmt, sinks));

    std::unique_ptr<lcglog::LoggerBuilder> builder(new lcglog::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(lcglog::LogLevel::value::ERROR);
    builder->buildLoggerFormatter("[%c]%m%n");
    builder->buildLoggerType(lcglog::LoggerType::LOGGER_ASYNC);
    builder->buildEnableUnsafeAsync();
    builder->buildSink<lcglog::FileSink>("./logfile/async.log");
    builder->buildSink<lcglog::StdoutSink>();
    builder->build();
    test_log();
    
    // lcglog::LogMsg msg(lcglog::LogLevel::value::DEBUG, 99, "main.c", "root", "格式化功能测试...");
    // // lcglog::Formatter fmt("%g%gab%g%g%g%gcd%%[%d{%H:%M:%S}]  %m%g%g%n");
    // lcglog::Formatter fmt;
    // std::string str=fmt.format(msg);
    // // std::cout <<"开始测试\n";
    // // std::cout << str << std::endl;
    // // lcglog::LogSink::ptr lsp_stdout=lcglog::SinKFactory::create<lcglog::StdoutSink>();
    // // lcglog::LogSink::ptr lsp_file=lcglog::SinKFactory::create<lcglog::FileSink>("./logfile/test_file");
    // // lcglog::LogSink::ptr lsp_rollfile=lcglog::SinKFactory::create<lcglog::RollBySizeSink>("./logfile/roll-", 1024*1024);
    // lcglog::LogSink::ptr lsp_timefile=lcglog::SinKFactory::create<RollByTimeSink>("./logfile/roll-", TimeGap::GAP_SECOND);

    // time_t old = lcglog::util::Date::now();
    // while(lcglog::util::Date::now() < old + 5){
    //     lsp_timefile->log(str.c_str(), str.size());
    //     usleep(1000);
    // }
    // lsp_stdout->log(str.c_str(), str.size());
    // lsp_file->log(str.c_str(), str.size());
    // size_t cutsize = 0;
    // size_t count = 0;
    // while(cutsize < 1024*1024*10){
    //     std::string tmp = str+std::to_string(count++);
    //     lsp_rollfile->log(tmp.c_str(), tmp.size());
    //     cutsize += tmp.size();
    // }

    
    // std::cout << lcglog::LogLevel::toString(lcglog::LogLevel::value::DEBUG) << std::endl;
    // std::cout << lcglog::LogLevel::toString(lcglog::LogLevel::value::INFO) << std::endl;
    // std::cout << lcglog::LogLevel::toString(lcglog::LogLevel::value::WARN) << std::endl;
    // std::cout << lcglog::LogLevel::toString(lcglog::LogLevel::value::ERROR) << std::endl;
    // std::cout << lcglog::LogLevel::toString(lcglog::LogLevel::value::FATAL) << std::endl;
    // std::cout << lcglog::LogLevel::toString(lcglog::LogLevel::value::OFF) << std::endl;
    

    // std::cout<<lcglog::util::Date::now()<<std::endl;
    // std::string pathname("./abc/bcd/a.txt");
    // lcglog::util::File::createDirectory(lcglog::util::File::path(pathname));

    return 0;
}